<?php
/**
 * DataPermissionService.php
 *
 * @copyright   2023 thingsworld.com.cn - All Rights Reserved
 * @link        http://thingsworld.com.cn/
 * @author      stiffer.chen <chenl@thingsworld.com.cn>
 * @created     2023-04-12 16:59:08
 * @modified    2023-04-12 16:59:08
 *
 */

namespace App\Services;

use App\Models\Project\Task;
use App\Models\RoleModel;
use App\Repositories\WarehouseRepo;

class DataPermissionService
{
    private $userId;
    private $userService;
    private $routeName;

    private $routes;

    public function __construct($userId)
    {
        $this->userId = $userId;
        $this->userService = new IdentityService($userId);
        $this->routeName = request()->route()->getName();
        $this->setRoutes();
    }

    private function setRoutes()
    {
        $routes = [
            'projects',
            'tasks',
            'warehouses',
            'inventory'
        ];
        $this->routes = $routes;
    }

    /**
     * 根据路由前缀验证数据权限
     */
    public function check()
    {
        if ($this->userId == 1) {
             return;
        }

        $route = $this->routeName;
        if (!$route) {
            return;
        }

        $routeArr = explode('.', $route);
        $routePrefix = $routeArr[0] ?? '';
        if (!$routePrefix) {
            return;
        }
        if (!in_array($routePrefix, $this->routes)) {
            return;
        }
        $method = 'check' . ucfirst($routePrefix);
        $this->$method();
    }

    /**
     * 库存检查
     * 仓库管理员: 入库、出库 、调拨、分配
     * 非仓库管理员: 申领
     */
    public function checkInventory()
    {
        $action = strtolower($this->getRouteAction());
        if (in_array($action, ['batch_inventory', 'single_storage', 'safe_quantity'])) {
            // 仓库管理员ID
            $warehouseManagerIds = WarehouseRepo::managerIds();
            if (!in_array($this->userId, $warehouseManagerIds)) {
                throw new \Exception('仅仓库管理员可以进行该操作');
            }
        }
    }

    // 仓库检查
    protected function checkWarehouses()
    {
        // 创建、修改: 超级管理员(role)
        $action = strtolower($this->getRouteAction());
        if ($action == 'store' || $action == 'update') {
            if (!$this->userService->isSuperUser()) {
                // throw new \Exception('当前账号没有权限创建或修改仓库');
            }
        }
    }

    public function checkTasks()
    {
        $positionInfo = $this->getPositionInfo();
        $positionName = trim($positionInfo->name ?? '');
        $action = $this->getRouteAction();
        if ($action == 'types' && $positionName != '项目经理') {
            // throw new \Exception('仅项目经理可以查看任务类型');
        }
        // 创建任务: 本项目负责人
        if ($action == 'store') {

        }
        if ($action == 'close') {
            $taskId = request('id');
            $task = Task::find($taskId);
            if (empty($task)) {
                throw new \Exception('任务不存在');
            }
            $project = $task->project;
            if (empty($project)) {
                throw new \Exception('任务所属项目不存在');
            }
            // 项目负责人
            $projectUserId = $project->user_id ?? 0;
            if ($projectUserId != $this->userId) {
                throw new \Exception('仅项目负责人可以执行该操作');
            }
        }

        /**
         * 项目负责人
         *      未开始: 关闭任务、编辑任务、删除任务
         *      进行中: 关闭任务、编辑任务、删除任务
         *      已关闭: 删除任务
         *      已完成: --
         * 任务负责人
         *      未开始: 开始任务
         *      进行中: 完成任务
         *      已关闭: 不可见
         *      已完成: --
         */


    }

    /**
     * 创建: 项目经理
     */
    public function checkProjects()
    {
        $positionInfo = $this->getPositionInfo();
        $action = $this->getRouteAction();
        if ($action == 'store') {
            $roleNames = $this->getRoleInfo();
            $accessRoles = ['项目经理', '区域主管', '区域总监'];
            if (!array_intersect($roleNames, $accessRoles)) {
                throw new \Exception('当前用户不能创建项目');
            }
        }
    }

    /**
     * 获取路由具体动作
     */
    private function getRouteAction()
    {
        $routeName = $this->routeName;
        $actionArr = explode('.', $routeName);
        $action = $actionArr[count($actionArr) - 1] ?? '';
        return $action ?? '';
    }

    // 获取登录用户部门信息
    private function getPositionInfo()
    {
        $service = new UserDataService($this->userId);
        return $service->getPosition();
    }

    // 登录用户角色信息
    private function getRoleInfo()
    {
        $roles = RoleModel::query()
            ->from('role as r')
            ->select(['r.name'])
            ->join('user_role as ur', 'r.id', '=', 'ur.role_id')
            ->where('ur.user_id', $this->userId)
            ->get();
        return $roles->pluck('name')->toArray();
    }
}